package com.iven.xie.redis.service.impl;

import com.iven.xie.redis.beans.CacheKey;
import com.iven.xie.redis.service.CacheService;
import com.iven.xie.redis.util.CacheTypeEnum;
import com.iven.xie.redis.util.JedisUtil;
import com.iven.xie.redis.util.PropertiesUtil;
import org.springframework.stereotype.Service;

import java.util.Properties;

import static com.iven.xie.redis.util.PropertiesUtil.DEFAULT_CONFIG;


/**
 * @author iven.xie
 */
@Service
public class CacheServiceImpl implements CacheService {

    /**
     * 当前系统配置生效的缓存类型
     */
    public static final CacheTypeEnum CACHE_TYPE;

    static {
        Properties prop = PropertiesUtil.loadProperties(DEFAULT_CONFIG);
        String cacheTypeStr = PropertiesUtil.getString(prop, "cache.type");
        CacheTypeEnum cacheType = CacheTypeEnum.match(cacheTypeStr);
        CACHE_TYPE = (cacheType != null) ? cacheType : CacheTypeEnum.Redis;
    }

    @Override
    public CacheTypeEnum getCacheType() {
        return CACHE_TYPE;
    }

    @Override
    public boolean set(CacheKey cacheKey, Object value) {
        // 针对缓存管理系统,暂时并不需要Set类型方法, 如若将本Service抽象成公共RPC服务, 可自行完善扩充
        return false;
    }

    /**
     * 查询缓存
     *
     * @param cacheKey
     * @return
     */
    @Override
    public Object get(CacheKey cacheKey) {
        switch (CACHE_TYPE) {
            case Redis:
                return JedisUtil.getObjectValue(cacheKey.getFinalKey());
            default:
                return null;
        }
    }

    /**
     * 清除缓存
     *
     * @param cacheKey
     * @return
     */
    @Override
    public boolean delete(CacheKey cacheKey) {
        switch (CACHE_TYPE) {
            case Redis:
                Long ret = JedisUtil.del(cacheKey.getFinalKey());
                return ret != null && ret > 0;
            default:
                return false;
        }
    }

}
